package com.ocom.human.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ocom.common.constant.HumanServiceUrl;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.entity.human.EntityRoommateInfo;
import com.ocom.common.entity.master.EntityWechatAppInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.*;
import com.ocom.common.utils.wx.WxGhUtils;
import com.ocom.common.vo.human.*;
import com.ocom.human.feignclient.PayConfigClientService;
import com.ocom.human.service.PersonnelInfoService;
import com.ocom.human.service.RoommateInfoService;
import com.ocom.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class RoommateController {
//    private final Logger log = LoggerFactory.getLogger(RoommateController.class);


    @Autowired
    private RoommateInfoService roommateInfoService;

    @Autowired
    private PersonnelInfoService personnelInfoService;

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private PayConfigClientService payConfigClientService;

//    @Autowired
//    private MqZhongyu mqZhongyu;

    /**
     * 获取同住人列表（getRoommateList）
     */
    @PostMapping(HumanServiceUrl.URL_GetRoommateList)
    public Result GetRoommateList(@Validated @RequestBody GetRoommateListVo getRoommateListVo) {
        log.info("获取同住人列表请求参数{{}}", getRoommateListVo);
        Map<String, Object> map = new HashMap<>();
        try {
            List<EntityRoommateInfo> entityRoommateInfos = roommateInfoService.GetRoommateList(getRoommateListVo.getComId(), getRoommateListVo);
            PageInfo<EntityRoommateInfo> entityRoommateInfoPageInfo = new PageInfo<>(entityRoommateInfos);
            map.put("total", entityRoommateInfoPageInfo.getTotal());
            map.put("list", entityRoommateInfos);
            log.info("获取同住人列表:{{}}", map);
        } catch (Exception exception) {
            log.error("获取同住人列表失败:{{}}", exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009, "获取同住人列表失败");
        }
        return ResultUtil.success(map);
    }

    /**
     * 新增同住人（addRoommate）
     */
    @PostMapping(HumanServiceUrl.URL_AddRoommate)
    public Result AddRoommate(@Validated @RequestBody EntityRoommateInfo entityRoommateInfo) {
        log.info("新增同住人请求参数{{}}", entityRoommateInfo);
        // 判断人员是否有效
        log.info("消息队列发送同住人员数据{{}}", entityRoommateInfo);
        if (!CommonUtil.isNull(entityRoommateInfo.getIdentity())) {
            if (!IdentificationCodeUtil.isIdentityCode(entityRoommateInfo.getIdentity())) {
                return ResultUtil.error(ResultEnum.Err_2021);
            }
        }
        //封装mq数据
//        Long companyId = entityRoommateInfo.getComId();
        //发送消息队列
//        mqZhongyu.Send(companyId,entityRoommateInfo.getIdentity(),entityRoommateInfo.getName());

        try {
            UserInfoYkmVo personInfoById = personnelInfoService.getPersonInfoById(entityRoommateInfo.getComId(), entityRoommateInfo.getPId());
            if (personInfoById == null) {
                return ResultUtil.error(ResultEnum.Err_1001, "添加失败，未找到指定学生");
            }
        } catch (Exception exception) {
            log.info("添加同住人员，查询人员信息失败");
            return ResultUtil.error(ResultEnum.Err_2009, "添加失败，未找到指定学生");
        }
        try {
//            entityRoommateInfo.setPhone(StringUtils.desValue(entityRoommateInfo.getPhone(),2,3,"*"));
//            entityRoommateInfo.setIdentity(StringUtils.desValue(entityRoommateInfo.getIdentity(),2,3,"*"));
            roommateInfoService.AddRoommate(entityRoommateInfo.getComId(), entityRoommateInfo);
        } catch (Exception exception) {
            log.error("新增同住人列表失败:{{}}", exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009, "新增同住人列表失败");
        }

        return ResultUtil.success();
    }

    /**
     * 删除同住人（removeRoommate）
     */
    @PostMapping(HumanServiceUrl.URL_RemoveRoommate)
    public Result RemoveRoommate(@Validated @RequestBody RemoveRoommateVo removeRoommateVo) {
        log.info("删除同住人请求参数{{}}", removeRoommateVo);
        if (StringUtils.isNull(removeRoommateVo.getComId())) {
            log.error("单位编号为空");
            return ResultUtil.error(ResultEnum.Err_203, "单位编号为空");
        }
        if (StringUtils.isNull(removeRoommateVo.getPId())) {
            log.error("人员编号为空");
            return ResultUtil.error(ResultEnum.Err_203, "人员编号为空");
        }
        try {
            roommateInfoService.RemoveRoommate(removeRoommateVo.getComId(), removeRoommateVo.getPId(), removeRoommateVo.getId());
        } catch (Exception exception) {
            log.error("删除同住人失败:{{}}", exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009, "删除同住人列表失败");
        }
        return ResultUtil.success();
    }

    @PostMapping(HumanServiceUrl.URL_addRoommateCode)
    public Result addRoommateCode(@Validated @RequestBody AddRoommateCodeVo request) throws IOException {
        log.info("生成联系人邀请码{{}}", request);
        Result wxInfo = payConfigClientService.getWxInfo(request.getComId(), 0l, "xcx");
        EntityWechatAppInfo entityWechatAppInfo = JSON.parseObject(JSON.toJSONString(wxInfo.getData()), EntityWechatAppInfo.class);

        String unlimited = null;
        if (entityWechatAppInfo != null) {
            String canKey = "xcxToken:" + entityWechatAppInfo.getAppid();
            Object tokenRedis = redisUtil.get(canKey);
            if (tokenRedis == null) {
                tokenRedis = WxGhUtils.getAccessToken(entityWechatAppInfo.getAppid(), entityWechatAppInfo.getAppsecret());
                if (tokenRedis != null) {
                    redisUtil.set(canKey, tokenRedis, 7000l);
                }
            }

            String comStr = NumConvertUtil.IntLegth(request.getComId().intValue(), 8);
            String pIdStr = NumConvertUtil.IntLegth(request.getPId().intValue(), 8);
            String staticCode = "XAK" + "_" + comStr + "_" + pIdStr;

//            String page = "pages/tel/tel"; //未发布
            String page = null;
            unlimited = WxGhUtils.getUnlimited((String) tokenRedis, page, staticCode);
        }
        return ResultUtil.success(unlimited);
    }

    /**
     * 导入同住人（ importBorders）
     */
    @PostMapping(HumanServiceUrl.URL_ImportBorders)
    public Result ImportBorders(Long comId, @Validated @RequestBody List<BoardersImportVo> boardersImportVos) {
        log.info("导入同住人请求参数{{}},comId{{}}", boardersImportVos, comId);
        List<EntityRoommateInfo> entityRoommateInfos = new ArrayList<>();
        List<String> pCode = boardersImportVos.stream().map(BoardersImportVo::getPCode).collect(Collectors.toList());
        List<EntityPersonnelInfo> personInfopCode = null;
        String key = MD5.MD5Encode(comId.toString(), "utf8");
        try {
            personInfopCode = personnelInfoService.getPersonInfopCode(comId, pCode);
        } catch (Exception exception) {
            log.error("查询人员列表失败:{{}}", exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009, "查询人员列表失败");
        }
        //封装同住人信息
        try {
            EntityRoommateInfo entityRoommateInfo = new EntityRoommateInfo();
            for (BoardersImportVo boardersImportVo : boardersImportVos) {
                if (boardersImportVo.getPCode() == null || boardersImportVo.getPCode().isEmpty()) {
                    continue;
                }
                if (!IdentificationCodeUtil.isIdentityCode(boardersImportVo.getIdentity())) {
                    log.info("{{}}身份证信息不合规{{}}", boardersImportVo.getName(), boardersImportVo.getIdentity());
                    continue;
                }
                for (EntityPersonnelInfo personnelInfo : personInfopCode) {
                    if (boardersImportVo.getPCode() != null && boardersImportVo.getPCode().equals(personnelInfo.getPCode())) {
                        roommateInfoService.RemoveRoommate(comId, personnelInfo.getPId(), null);
                        entityRoommateInfo.setPId(personnelInfo.getPId());
                    }
                }

                entityRoommateInfo.setComId(comId);
                entityRoommateInfo.setName(boardersImportVo.getName());

                entityRoommateInfo.setType(boardersImportVo.getType());
                entityRoommateInfo.setPhone(StringUtils.desValue(boardersImportVo.getPhone(), 2, 3, "*"));
                entityRoommateInfo.setIdentity(StringUtils.desValue(boardersImportVo.getIdentity(), 2, 3, "*"));
                entityRoommateInfo.setEncryPhone(AES.encrypt(boardersImportVo.getPhone(), key));
                entityRoommateInfo.setEncryIdentity(AES.encrypt(boardersImportVo.getIdentity(), key));
                entityRoommateInfo.setName(boardersImportVo.getName());
                //封装mq数据
                Long companyId = comId;
                //发送消息队列
//                mqZhongyu.Send(companyId,boardersImportVo.getIdentity(),boardersImportVo.getName());

                entityRoommateInfos.add(entityRoommateInfo);
            }
        } catch (Exception exception) {
            log.error("封装同住人信息失败:{{}}", exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009, "封装同住人信息失败");
        }

        try {
            roommateInfoService.ImportBorders(comId, entityRoommateInfos);
        } catch (Exception exception) {
            log.error("新增同住人列表失败:{{}}", exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009, "新增同住人列表失败");
        }
        return ResultUtil.success();
    }

    /**
     * 获取学生列表  personnel/getStudentInfo
     */
    @PostMapping(HumanServiceUrl.URL_PersonnelGetStudentInfo)
    public Result PersonnelGetStudentInfo(@Validated @RequestBody GetStudentInfoVo getStudentInfoVo) {
        log.info("获取学生列表请求参数:{{}}", getStudentInfoVo);
        Map<String, Object> map = new HashMap<>();
        try {

            List<StudentInfoRVo> studentInfoRVos = roommateInfoService.PersonnelGetStudentInfo(getStudentInfoVo.getComId(), getStudentInfoVo);
            PageInfo<StudentInfoRVo> studentInfoRVoPageInfo = new PageInfo<>(studentInfoRVos);
            map.put("total", studentInfoRVoPageInfo.getTotal());
            map.put("list", studentInfoRVos);
        } catch (Exception exception) {
            log.error("获取学生列表失败:{{}}", exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009, "获取学生列表失败");
        }
        log.info("获取学生列表{{}}", map);
        return ResultUtil.success(map);
    }

    @PostMapping(HumanServiceUrl.URL_updateStudentByInOut)
    public Result updateStudentByInOut(@RequestBody JSONObject jsonObject) {
        try {
            boolean i = personnelInfoService.updateStudentInfo(jsonObject.getLong("comId"), jsonObject);
            if (i) {
                return ResultUtil.success();
            } else {
                return ResultUtil.error(ResultEnum.Err_3026);
            }
        } catch (Exception exception) {
            log.error("修改学生出入状态:{{}}", exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009, "修改学生出入状态");
        }
    }
}
